#include <iostream>
#include <mongocxx/instance.hpp>
#include <mongocxx/client.hpp>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>

int main(int argc, char const *argv[])
{
    if(2 != argc ){
        std::cout<<"./main 1|2|3|4 ---- 1-insert,2-remove,3-update,4-query"<<std::endl;
        return -1;
    }
    int op = atoi(argv[1]);

    mongocxx::instance instance{};
    mongocxx::uri uri("mongodb://localhost:27017");
    mongocxx::client client(uri);
    mongocxx::database db = client["yekai"]; //use
    // mongocxx::collection collection = db["langzi"];
    mongocxx::collection collection = db["Barca"];

    auto document = bsoncxx::builder::stream::document{};
    if(1 == op){
        //insert
        bsoncxx::document::value doc_value = document
        <<"id"<<"5"
        <<"name"<<"yekai"
        <<bsoncxx::builder::stream::finalize;

        bsoncxx::document::view view = doc_value.view();
        collection.insert_one(view);
    }else if(2 == op){
        //delete
        bsoncxx::stdx::optional<mongocxx::result::delete_result> result 
            = collection.delete_many(
                document<<
                    "id"<<
                            bsoncxx::builder::stream::open_document<<
                            "$gte"<<1<<
                            bsoncxx::builder::stream::close_document
                    // "id"<<"5"
                <<bsoncxx::builder::stream::finalize);
        if(result){
            std::cout<<result->deleted_count()<<std::endl;
        } 
    }else if(3 == op){
        //update
        collection.update_one(document<<"id"<<"5"<<bsoncxx::builder::stream::finalize, //查询条件的json
        document<<"$set"<<bsoncxx::builder::stream::open_document<<"name"<<"fuhonxue"
        <<bsoncxx::builder::stream::close_document<<bsoncxx::builder::stream::finalize); //修改的json
    }else if(4 == op){
        mongocxx::cursor cursor = collection.find({});
        for (auto&& doc : cursor) {
            std::cout << bsoncxx::to_json(doc) << std::endl;
         }
    }
    return 0;
}
